import axios from 'axios'
import { Toast, Dialog } from 'vant'
import { getLocations, setLocations } from '@/utils/storage'
import router from '@/router';

function goLogin() {
  const { currentRoute } = router
  if (currentRoute.value.path !== '/login') {
    router.push({
      path: '/login',
      query: {
        redirect: currentRoute.value && currentRoute.value.fullPath
      }
    })
  }
}

// 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // timeout: 5000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (!config.hideLoading) {
      Toast.loading({
        forbidClick: true,
      });
    }
    config.headers = {
      ...config.headers,
      Authorization: 'Basic c2FiZXI6c2FiZXJfc2VjcmV0'
    }
    const accessToken = getLocations('accessToken')
    if (accessToken) {
      config.headers['Blade-Auth'] = `bearer ${accessToken}`
    }
    const enterType = getLocations('enterType')
    if (enterType) {
      config.headers['enterType'] = enterType
    }
    return config
  },
  error => {
    // 请求错误，可在此进行统一错误处理
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    const config = response.config
    if (res.code !== 200 && !config.noErrorTip && res.status != 1 ) {
      let errorMsg = res.msg || '系统异常，请联系客服'
      if (res.code === 401) {
        errorMsg = '请填写手机号和验证码'
      }
      Toast.fail({
        message: errorMsg,
        duration: 5 * 1000
      })
    }

    if (res.code === 401) {
      setLocations('accessToken', '');
      goLogin();
      return res
    }
    return res
  },
  error => {
    Toast.clear()
    console.log('err' + error) // for debug
    Toast.fail({
      message: error.message || '系统错误！',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
